
window.auth = {

    getToken: function () {
        return localStorage.getItem('token') || sessionStorage.getItem("token")
    },

    clearToken: function () {
        localStorage.removeItem('token');
        sessionStorage.removeItem('token');
    },

    isTokenValid: function () {
        const token = this.getToken();
        if (!token) return false;

        try {
            const payload = JSON.parse(atob(token.split(".")[1]));
            const currentTime = Math.floor(Date.now() / 1000);
            return payload.exp && payload.exp > currentTime;
        } catch (error) {
            console.error('Token解析失败：', error)
            return false;
        }
    },


    handleLogout: function (message = "请先登录") {
        layui.use('layer', function () {
            const layer = layui.layer;
            layer.msg(message), {
                icon: 2,
                time: 2000
            }, function () {
                location.href = "index.html"
            };
        });
    },

    checkLogin: function () {
        if (!this.isTokenValid()) {
            this.handleLogout();
            return false;
        }
        return true;
    },

    checkLoginAsync: function () {
        const token = this.getToken();
        if (!token) {
            callback(false);
            return;
        }

        layui.use('juqery', function () {
            const $ = layui.jquery;
            $.ajax({
                url: apiConfig.baseUrl + '/check/token/',
                type: 'GET',
                Headers: {
                    'Authorization': `Bearer ${token}`
                },
                success: function (res) {
                    callback(true)
                },
                error: function (xhr) {
                    if (xhr.status === 401) {
                        callback(false)
                    } else {
                        callback(false)
                    }

                }
            })
        })
    },
}